def display_menu(menu):
    """展示食堂菜单"""
    print("\n===== 食堂今日菜单 =====")
    print("编号 | 菜品名称 | 价格(元)")
    print("-" * 30)
    for idx, (name, price) in enumerate(menu.items(), 1):
        print(f"{idx:2d}   | {name:6s}   | {price:.2f}")
    print("-" * 30)


def get_valid_input(prompt, valid_range=None):
    """获取有效的用户输入"""
    while True:
        try:
            user_input = input(prompt)
            # 如果需要数字输入
            if valid_range is not None:
                num = int(user_input)
                if num in valid_range:
                    return num
                else:
                    print(f"请输入{valid_range}范围内的数字")
            else:
                # 非数字输入直接返回
                return user_input.strip().lower()
        except ValueError:
            print("输入格式错误，请重新输入")


def main():
    # 初始化菜单（可以根据实际情况扩展）
    menu = {
        "红烧肉": 18.00,
        "鱼香肉丝": 12.00,
        "番茄炒蛋": 8.00,
        "清炒时蔬": 6.00,
        "紫菜蛋汤": 5.00,
        "米饭": 2.00
    }
    
    order = {}  # 存储订单 {菜品: (价格, 数量)}
    menu_keys = list(menu.keys())
    menu_size = len(menu_keys)
    
    print("欢迎来到食堂点餐系统！")
    
    while True:
        display_menu(menu)
        
        # 选择菜品
        print("\n请选择操作：")
        print(f"1-{menu_size}: 选择对应编号的菜品")
        print(f"{menu_size + 1}: 查看已点菜品")
        print(f"{menu_size + 2}: 确认订单并结算")
        print(f"{menu_size + 3}: 取消订单并退出")
        
        choice_range = range(1, menu_size + 4)
        choice = get_valid_input(f"请输入(1-{menu_size + 3}): ", choice_range)
        
        # 处理选择
        if 1 <= choice <= menu_size:
            # 选择了菜品
            dish_name = menu_keys[choice - 1]
            dish_price = menu[dish_name]
            
            # 输入数量
            while True:
                quantity = get_valid_input(f"请输入{ dish_name }的数量(至少1份): ", range(1, 100))
                if quantity >= 1:
                    break
                print("数量必须大于等于1")
            
            # 添加到订单
            if dish_name in order:
                order[dish_name] = (dish_price, order[dish_name][1] + quantity)
            else:
                order[dish_name] = (dish_price, quantity)
            
            print(f"已添加 {dish_name} x {quantity}")
        
        elif choice == menu_size + 1:
            # 查看已点菜品
            if not order:
                print("您还没有点任何菜品")
                continue
                
            print("\n===== 已点菜品 =====")
            print("菜品名称 | 单价 | 数量 | 小计")
            print("-" * 30)
            total = 0
            for name, (price, quantity) in order.items():
                subtotal = price * quantity
                total += subtotal
                print(f"{name:6s}   | {price:.2f} | {quantity:2d}  | {subtotal:.2f}")
            print("-" * 30)
            print(f"总计: {total:.2f}元")
        
        elif choice == menu_size + 2:
            # 确认订单并结算
            if not order:
                print("您还没有点任何菜品，无法结算")
                continue
                
            # 显示订单
            print("\n===== 订单确认 =====")
            total = 0
            for name, (price, quantity) in order.items():
                subtotal = price * quantity
                total += subtotal
                print(f"{name} x {quantity}: {subtotal:.2f}元")
            print(f"总计: {total:.2f}元")
            
            # 确认支付
            confirm = get_valid_input("确认支付吗？(y/n): ")
            if confirm == 'y':
                print(f"\n支付成功！总计支付 {total:.2f}元")
                print("感谢您的光临，祝您用餐愉快！")
                break
            else:
                print("已取消支付，继续点餐")
        
        elif choice == menu_size + 3:
            # 取消订单并退出
            if order:
                confirm = get_valid_input("确定要取消订单并退出吗？(y/n): ")
                if confirm == 'y':
                    print("已取消订单，欢迎下次光临！")
                    break
            else:
                print("欢迎下次光临！")
                break


if __name__ == "__main__":
    main()